package com.bojiu.lawsearch.lawsearch.controller;

import com.bojiu.lawsearch.lawsearch.wxzf.PayResultHandler;
import com.bojiu.lawsearch.lawsearch.wxzf.WXZFUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author: afdiao
 * @Date：2020/3/31 14:27
 * @Description:
 */
@RestController
@Slf4j
public class WxzfController {

    @Autowired
    PayResultHandler payResultHandler;

    @PostMapping("zfRedirect")
    public String zfRedirect(HttpServletRequest request) {
        try {
            BufferedReader reader = null;
            reader = request.getReader();
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String result = buffer.toString();
            result = new String(result.getBytes("ISO-8859-1"), "UTF-8");
            log.debug("body is :{}", result);
            Map<String, String> informMap = WXZFUtil.processResponseXml(result);
            log.debug("接受通知成功,map is :{}", informMap);
            //异步处理通知
            payResultHandler.handle(informMap);
//			 返回通知结果给微信
            String returnCode = informMap.get("return_code");
            String returnMsg = informMap.get("return_msg");
            Map<String, String> rerurnMap = WXZFUtil.createInfromData(returnCode, "支付成功OK~");
            String returnStr = WXZFUtil.mapToXml(rerurnMap);
            returnStr = returnStr.replaceAll("&lt;", "<");
            returnStr = returnStr.replaceAll("&gt;", ">");
            return returnStr;
        } catch (Exception e) {
            log.error("error to get wxzfInfo,error is :{}", e);
            return "false";
        }
    }

}
